from django.conf import settings


def init_permission(request, user):
    '''
    # 菜单和权限初始化,登录成功以后调用该方法将菜单和权限存入session
    :param request:
    :param user: 用户对象
    :return:
    '''
    # 获取当前用户的权限url(去重之后) QuerySet集合可以再度查询
    # 实际上要拿到当前用户所有的角色的所有的权限
    # permissions__menu_id --- 菜单表的id _就行，这个表其他的字段需要__
    permissions_queryset = user.roles.filter(permissions__url__isnull=False).values('permissions__id',
                                                                                    'permissions__url',
                                                                                    'permissions__title',
                                                                                    'permissions__name',
                                                                                    'permissions__parent_id',
                                                                                    'permissions__parent__name',
                                                                                    'permissions__menu_id',
                                                                                    'permissions__menu__title',
                                                                                    'permissions__menu__icon'
                                                                                    ).distinct()
    menu_dicts = {}  # 能成为菜单的权限
    permissions_dict = {}  # 当前用户的所有权限
    for row in permissions_queryset:
        # 添加的权限信息--自己的id 其父亲的id(可以为空) 当前用户的权限url
        permissions_dict[row['permissions__name']] = {
            'id': row['permissions__id'],
            'pid': row['permissions__parent_id'],
            'pname': row['permissions__parent__name'],
            'url': row['permissions__url'],
            'title': row['permissions__title'],
        }
        menu_id = row.get('permissions__menu_id')
        if not menu_id:
            continue
        if menu_id not in menu_dicts:
            menu_dicts[menu_id] = {
                'title': row['permissions__menu__title'],
                'icon': row['permissions__menu__icon'],
                'children': [
                    {'id': row['permissions__id'], 'title': row['permissions__title'], 'url': row['permissions__url']}
                ]
            }
        else:
            menu_dicts[menu_id]['children'].append(
                {'id': row['permissions__id'], 'title': row['permissions__title'], 'url': row['permissions__url']})
    # 权限列表生成
    # print(permissions_dict)
    request.session[settings.PERMISSIONS_LIST] = permissions_dict
    # 菜单生成
    request.session[settings.MENU_LIST] = menu_dicts
